<template>
  <div class="ai-exam">
    <div class="step-two">
      <div class="two-search-box">
        <div class="two-search">
          <div>时间段：</div>
          <el-date-picker
            v-model="form.startTime"
            type="date"
            size="large"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="开始时间"
          />
          -
          <el-date-picker
            v-model="form.endTime"
            type="date"
            size="large"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="结束时间"
          />
          <div class="search-btn" @click="search">搜索</div>
        </div>
        <div class="two-btns">
          <div class="all-btn" @click="handleAddAgent()">
            <el-icon>
              <CirclePlus />
            </el-icon>
            添加考核智能体
          </div>
          <!-- <div
            class="all-btn"
            @click="$router.push('/zhinengti')"
          >
            <el-icon>
              <ArrowLeft />
            </el-icon>
            返回上一级
          </div> -->
        </div>
      </div>
      <div class="all-box-container">
        <div>
          <el-table :data="tableData" style="width: 100%">
            <!-- 加序号 -->
            <el-table-column
              label="序号"
              type="index"
              width="100"
              :index="calculateIndex"
            ></el-table-column>
            <el-table-column prop="agentName" label="考核类型" width="250" />
            <el-table-column
              label="章节/考核知识点"
              show-overflow-tooltip
              width="450"
            >
              <template #default="scope">
                <div
                  v-if="scope.row.chapterNames.length > 0"
                  class="chapter-names"
                >
                  <div v-for="item in scope.row.chapterNames" :key="item">
                    {{ item }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="cronTime" label="考核时间" width="400" />
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  size="small"
                  text
                  type="primary"
                  @click="handleEditAgent(scope.row)"
                  style="color: #457aff; font-size: 14px"
                >
                  修改
                </el-button>
                <el-button
                  style="margin-left: 0px; color: #457aff; font-size: 14px"
                  text
                  type="primary"
                  size="small"
                  @click="delAgent(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="all-page">
            <el-pagination
              v-model:current-page="form.page"
              :page-size="10"
              layout="prev, pager, next, jumper"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" width="830" :before-close="handleClose">
      <div class="my-dialog">
        <div v-if="isEdit" class="my-dialog-title">修改考核智能体</div>
        <div v-else class="my-dialog-title">添加考核智能体</div>
        <div class="my-dialog-content">
          <div>
            <div class="item-label"><span class="red">*</span>考核类型：</div>
            <div class="item-content">
              <el-select
                v-model="addForm.agentName"
                placeholder="请选择"
                size="large"
              >
                <el-option
                  v-for="item in agentOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </div>
          </div>
          <div>
            <div class="item-label">考核时间：</div>
            <div class="item-content time-picker">
              <el-date-picker
                v-model="addForm.cronTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择"
                size="large"
              />
            </div>
          </div>
          <div>
            <div class="item-label">
              <span class="red">*</span>考核章节/知识点：
            </div>
            <div class="item-content">
              <el-cascader
                v-model="addForm.knowIds"
                :options="knowList"
                :props="props"
                collapse-tags
                collapse-tags-tooltip
                clearable
                size="large"
                popper-class="cascader-box"
              >
                <template #default="{ data }">
                  <div class="cascader-node">
                    <span class="node-label">{{ data.label }}</span>
                    <span v-if="data.questionCount" class="question-count">
                      {{ data.questionCount }}道
                    </span>
                  </div>
                </template>
              </el-cascader>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="isEdit" color="#155EEF" @click="editAgent()">
            修改
          </el-button>
          <el-button v-else color="#155EEF" @click="addAgent()">
            确定
          </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import eventBus from "@/utils/eventBus";
import { id } from "element-plus/es/locales.mjs";

export default {
  data() {
    return {
      courseId: "",
      classId: "",
      isEdit: false,
      loading: false,
      dialogVisible: false,
      total: 0,
      form: {
        startTime: "",
        endTime: "",
        page: 1,
        limit: 10,
      },
      addForm: {
        agentName: "",
        cronTime: "",
        knowIds: [],
        id: "",
      },
      tableData: [],
      agentOptions: ["课前预习", "随堂练习", "课后复习"],
      props: {
        //是否多选
        multiple: true,
        //false只展示最后一级id，true展示所有层级
        emitPath: false,
        value: "value",
        label: "label",
        children: "children",
      },
      knowList: [],
    };
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.classId = JSON.parse(localStorage.getItem("classId"));
    this.getList();
    this.getKnowlist();

    // 监听班级变更事件
    eventBus.on("classChanged", this.handleClassChanged);
  },
  beforeUnmount() {
    // 清理事件监听器
    eventBus.off("classChanged", this.handleClassChanged);
  },
  methods: {
    // 计算表格序号
    calculateIndex(index) {
      return (this.form.page - 1) * this.form.limit + index + 1;
    },

    // 处理班级变更事件
    handleClassChanged(newClassId) {
      this.classId = newClassId;
      this.form.page = 1; // 重置页码
      this.getList(); // 重新获取数据
    },
    clearAddForm() {
      this.addForm = {
        agentName: "",
        cronTime: "",
        knowIds: [],
      };
    },
    search() {
      //如果结束日期小于起始日期，则提示错误，日期格式为YYYY-MM-DD，转换为时间戳
      if (new Date(this.form.startTime) > new Date(this.form.endTime)) {
        this.$message.error("结束日期不能小于起始日期");
        return;
      }
      this.form.page = 1;
      this.getList();
    },
    handleClose() {
      this.dialogVisible = false;
    },
    handleCurrentChange(currentPage) {
      this.form.page = currentPage;
      this.getList();
    },
    handleAddAgent() {
      this.isEdit = false;
      this.clearAddForm();
      this.dialogVisible = true;
    },
    handleEditAgent(row) {
      if (!row.edit) {
        this.$message.warning("考核已开始，无法修改");
        return;
      }
      this.isEdit = true;
      this.clearAddForm();
      this.addForm.agentName = row.agentName;
      this.addForm.cronTime = row.cronTime;
      this.addForm.knowIds = row.kbIds;
      this.addForm.id = row.id;
      this.dialogVisible = true;
    },
    getList() {
      const url = "/tes/dify/agent/list";
      const params = {
        startTime: this.form.startTime,
        endTime: this.form.endTime,
        page: this.form.page,
        limit: this.form.limit,
        courseId: this.courseId,
        classId: this.classId,
      };

      this.loading = true;
      this.$axios
        .get(url, {
          params, // 将参数传递给 `params` 属性
        })
        .then((response) => {
          const res = response;
          this.tableData = res.data.content;
          this.total = res.data.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    getKnowlist() {
      const url = `/tes/course/auto/make/chapter-kb?courseId=${this.courseId}&showQusNum=1`;
      this.loading = true;
      this.$axios
        .get(url)
        .then((response) => {
          const res = response;
          // 处理数据，将题目数量添加到标签中
          this.knowList = this.processKnowledgeData(res.data);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 处理知识点数据，将题目数量添加到标签中
    processKnowledgeData(data) {
      const processNode = (node) => {
        if (node.questionNum && node.questionNum > 0) {
          // 创建自定义标签，包含题目数量
          node.label = node.label;
          node.questionCount = node.questionNum;
        }

        if (node.children && node.children.length > 0) {
          node.children.forEach((child) => processNode(child));
        }

        return node;
      };

      return data.map((item) => processNode(item));
    },
    addAgent() {
      if (!this.addForm.agentName) {
        this.$message.error("请选择智能体");
        return;
      }
      if (this.addForm.knowIds.length === 0) {
        this.$message.error("请选择知识点");
        return;
      }
      // 处理级联选择器只选择一级节点的情况，过滤掉null值
      const filteredKnowIds = this.addForm.knowIds.filter(
        (id) => id !== null && id !== undefined
      );

      const url = "/tes/dify/agent/add";
      const data = {
        agentName: this.addForm.agentName,
        cronTime: this.addForm.cronTime,
        knowIds: filteredKnowIds,
        courseId: this.courseId,
        classId: this.classId,
      };
      const loading = this.$loading({
        lock: true,
        text: "正在添加，请稍后...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$axios
        .post(url, data)
        .then((response) => {
          const res = response;
          this.$message.success("添加成功");
          this.dialogVisible = false;
          this.getList();
        })
        .finally(() => {
          loading.close();
        });
    },
    editAgent() {
      if (!this.addForm.agentName) {
        this.$message.error("请选择智能体");
        return;
      }
      if (this.addForm.knowIds.length === 0) {
        this.$message.error("请选择知识点");
        return;
      }
      // 处理级联选择器只选择一级节点的情况，过滤掉null值
      const filteredKnowIds = this.addForm.knowIds.filter(
        (id) => id !== null && id !== undefined
      );

      const url = "/tes/dify/agent/edit";
      const data = {
        id: this.addForm.id,
        agentName: this.addForm.agentName,
        cronTime: this.addForm.cronTime,
        knowId: filteredKnowIds.join(","),
      };
      const loading = this.$loading({
        lock: true,
        text: "正在修改，请稍后...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$axios
        .post(url, data)
        .then((response) => {
          const res = response;
          this.$message.success("修改成功");
          this.dialogVisible = false;
          this.getList();
        })
        .finally(() => {
          loading.close();
        });
    },
    delAgent(row) {
      const url = `/tes/dify/agent/delete?id=${row.id}`;
      this.$confirm("是否删除该考核智能体？").then(() => {
        const loading = this.$loading({
          lock: true,
          text: "正在修改，请稍后...",
          background: "rgba(0, 0, 0, 0.7)",
        });
        this.$axios
          .delete(url)
          .then((response) => {
            const res = response;
            this.$message.success(res.msg || "删除成功");
            this.getList();
          })
          .finally(() => {
            loading.close();
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.ai-exam {
  background-color: #fff;
  padding: 40px 40px 40px 60px;
  box-sizing: border-box;
  min-height: 650px;
  .step-one {
    margin-bottom: 33px;
  }
  .step-two {
    .all-box-container {
      padding: 38px 0;
    }
    .all-btn {
      height: 36px;
      line-height: 36px;
      background: #457aff;
      border-radius: 4px;
      color: #fff;
    }
    .two-search-box {
      display: flex;
      justify-content: space-between;
    }
    .two-search {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 10px;
      :deep(.el-input__inner) {
        height: 38px;
      }
      .search-btn {
        font-size: 14px;
        color: #457aff;
        background-color: #fff;
        border: 1px solid #a5beff;
        border-radius: 4px;
        width: 60px;
        height: 38px;
        text-align: center;
        line-height: 38px;
        cursor: pointer;
      }
    }
    .two-btns {
      display: flex;
      gap: 10px;
    }
    .el-table {
      margin-bottom: 20px;
      :deep(th) {
        color: #7a8cb0;
      }
      .table-btns {
        display: flex;
        gap: 20px;
        font-size: 14px;
        > div {
          cursor: pointer;
          color: #457aff;
          &:hover {
            color: #2657b8;
          }
        }
      }
      .chapter-names {
        display: flex;
        gap: 10px;
      }
    }
  }
  .my-dialog {
    .my-dialog-title {
      padding: 0 48px;
      font-size: 20px;
      color: #204077;
      margin-bottom: 35px;
    }
    .my-dialog-content {
      display: flex;
      flex-direction: column;
      gap: 20px;
      padding: 20px 0 40px;
      > div {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 24px;
        .item-label {
          width: 150px;
          text-align: right;
          font-size: 16px;
          color: #000000;
          .red {
            color: red;
            margin-right: 4px;
          }
        }
        .item-content {
          :deep(.el-input) {
            width: 400px;
          }
          :deep(.el-select) {
            width: 400px;
          }
        }
      }
    }
  }
}
</style>

<style lang="scss">
.cascader-box {
  .cascader-node {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .question-count {
      height: 20px;
      line-height: 20px;
      padding: 0px 8px;
      background-color: #eaedfc;
      color: #457aff;
      border-radius: 15px;
    }
  }
}
</style>